//
//  HDMapViewController.m
//  HDecoration
//
//  Created by 曹群 on 15/8/25.
//  Copyright (c) 2015年 HDecoration. All rights reserved.
//

#import "HDMapViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "HDCustomAnnotationView.h"
#import "HDAnnotation.h"

@interface HDMapViewController ()
@property(nonatomic,strong)MKMapView *mapView;
@property(nonatomic,strong)UITextField *addressField;
@property(nonatomic,strong)UIButton *confirmBtn;
@property(nonatomic,strong)CLLocationManager *locationManager;
@property(nonatomic,strong) HDAnnotation *annotation;
@property (nonatomic)  CLGeocoder *geocoder;
@property (nonatomic)  CLLocation *location;
@property BOOL firstLocation;
@end

@implementation HDMapViewController
@synthesize annotation,locationManager;
@synthesize addressField,mapView;

- (void)initUI
{
    self.firstLocation=YES;
    self.view.backgroundColor = kContentViewColor;
    self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 74, self.view.width, APPFRAME.size.height-54)];
    self.mapView.delegate = (id)self;
    mapView.showsUserLocation = YES;
    mapView.mapType = MKMapTypeStandard;
    [self.view addSubview:mapView];
    
    UITapGestureRecognizer *mTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapPress:)];
    [mapView addGestureRecognizer:mTap];
    
    self.addressField = [[UITextField alloc] initWithFrame:CGRectMake(15, 94, APPFRAME.size.width-75, 40)];
    self.addressField.backgroundColor = [UIColor whiteColor];
    self.addressField.layer.borderColor = [UIColor colorWithRed:0.8235 green:0.8235 blue:0.8314 alpha:1].CGColor;
    self.addressField.layer.cornerRadius = 5;
    self.addressField.layer.borderWidth = 0.5;
    self.addressField.font = [UIFont systemFontOfSize:15];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, self.addressField.height)];
    self.addressField.leftViewMode = UITextFieldViewModeAlways;
    self.addressField.leftView = leftView;
    [self.view addSubview:self.addressField];
    
    self.confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.confirmBtn.frame = CGRectMake(self.addressField.right+5, self.addressField.top, 40, 40);
    [self.confirmBtn setBackgroundImage:[UIImage imageNamed:@"确定按钮"] forState:UIControlStateNormal];
    [self.confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    self.confirmBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.confirmBtn addTarget:self action:@selector(confirmAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.confirmBtn];
    
    [self startUpdatingLocation];
}

- (void)tapPress:(UIGestureRecognizer*)gestureRecognizer
{
    if (self.mapView.showsUserLocation &&(self.annotation==nil||self.annotation.tag==0))
    {
        return;
    }
    
    if(self.mapView.showsUserLocation)
    {
       self.mapView.showsUserLocation=NO;
    }
    else
    {
      [self.mapView removeAnnotation:self.annotation];
    }
    
    CGPoint touchPoint = [gestureRecognizer locationInView:mapView];
    CLLocationCoordinate2D touchMapCoordinate =[mapView convertPoint:touchPoint toCoordinateFromView:mapView];
    self.annotation.coordinate=touchMapCoordinate;
    [self.mapView addAnnotation:self.annotation];
    [self showAddressTip];
}


-(CLGeocoder *)geocoder
{
    if (_geocoder==nil)
    {
        _geocoder=[[ CLGeocoder alloc ] init ];
    }
    return _geocoder;
}

-(CLLocation *)location
{
    if (_location==nil)
    {
        _location=[[ CLLocation
                    alloc ] init ];
    }
    return _location;
}

-( void )showAddressTip
{
    CLLocation *newLocation=[[ CLLocation alloc ] initWithLatitude :self.annotation.coordinate.latitude longitude : self.annotation.coordinate.longitude ];
    [self.geocoder reverseGeocodeLocation :newLocation completionHandler :^( NSArray * placemarks, NSError * error)
     
    {
        MKPlacemark *placemark = [placemarks objectAtIndex : 0 ];
        
        NSString* path=@"";
        if (placemark. locality.length) {
            path=[path stringByAppendingString:placemark. locality];
        }
        if (placemark. subLocality.length) {
            path=[path stringByAppendingString:placemark. subLocality];
        }
        if (placemark. thoroughfare.length) {
            path=[path stringByAppendingString:placemark. thoroughfare];
        }
        if (placemark. subThoroughfare.length) {
            path=[path stringByAppendingString:placemark. subThoroughfare];
        }
        
        self.addressField.text = path;
        
    }];
    
}

- (void)confirmAction:(UIButton *)sender
{
    if (self.annotation!=nil)
    {
        [self requestUploadLocation];
    }
}


- (void)requestUploadLocation
{
    //教练位置上传请求
    NSDictionary* params=@{
                           @"id":netEngine.coachInfo.m_id,
                           @"xy":[NSString stringWithFormat:@"(%f,%f)",self.annotation.coordinate.latitude,self.annotation.coordinate.longitude],
                           @"address":self.addressField.text,
                           };
    [netEngine RequestUpdateSiteWithTarget:self.VctrID hudView:self.contentView Data:params];
}


- (void)dealloc
{
    self.geocoder=nil;
}

- (void)updateViewController:(NSNotification *)note
{
    NSDictionary *dic = note.userInfo;
    if ([dic objectForKey:Receiver]==self.VctrID) {
        if ([dic objectForKey:@"UpdateSite"]!=nil)
        {
            netEngine.coachInfo.address = self.addressField.text;
            netEngine.coachInfo.xy = [NSString stringWithFormat:@"(%f,%f)",self.annotation.coordinate.latitude ,self.annotation.coordinate.longitude];
        }
    }
}



-(void)startUpdatingLocation
{
    if (self.locationManager==nil)
    {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = (id)self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        CLLocationDistance distance=100.0;
        locationManager.distanceFilter=distance;
    }
    
    if (![CLLocationManager locationServicesEnabled])
    {
        [HDUtil showTipAlertWithMsg:@"定位服务当前可能尚未打开，请设置打开！"];
        return;
    }
    
    //如果没有授权则请求用户授权
    if (![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied)
    {
        [self showJumpToSettingView];
    }
    else
    {
        if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
        {
            [self.locationManager requestWhenInUseAuthorization];
        }
       
        [self.locationManager startUpdatingLocation];
    }
}


//定位服务未开启弹出的提示框
- (void)showJumpToSettingView
{
    UIAlertView *locationAlert = [[UIAlertView alloc] initWithTitle:@"定位服务未开启" message:@"\n请前往 [设置] → [隐私] → [定\n位服务] 开启定位服务" delegate:self cancelButtonTitle:@"暂不" otherButtonTitles:@"去设置", nil];
    [locationAlert show];
    locationAlert.tag = 101;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==101&&buttonIndex==1)
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString: UIApplicationOpenSettingsURLString]];
    }
}


- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    [locationManager stopUpdatingLocation];
}

#pragma mark MKMapViewDelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)m_annotation
{
    
    if (self.annotation==nil)
    {
        self.annotation=[[HDAnnotation alloc] initWithCoordinate:m_annotation.coordinate addressDictionary:nil];
    }
    else
    {
        self.annotation.coordinate=m_annotation.coordinate;
    }
    
    static NSString * const kAnnotationViewIdentifier = @"kAnnotationViewIdentifier";
    HDCustomAnnotationView *annotationView = ( HDCustomAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:kAnnotationViewIdentifier];

    if (annotationView)
    {
        annotationView.annotation = self.annotation;
    }
    else
    {
        annotationView = [[HDCustomAnnotationView alloc]initWithAnnotation:self.annotation reuseIdentifier:kAnnotationViewIdentifier];
    }
    
    if (self.firstLocation)
    {
        MKCoordinateSpan span = {0.01,0.01};
        MKCoordinateRegion region = { self.annotation.coordinate,span};
        [self.mapView setRegion:region animated:YES];
        [self showAddressTip];
        self.firstLocation=NO;
        self.annotation.tag=1;
    }
    
    return annotationView;
}


@end




















